package net.youpo.Market.UI.Manager;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import net.youpo.Market.MarketApplication;
import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Download.DownloadManager;
import net.youpo.Market.Download.Downloads;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AppManagerAdapter extends BaseExpandableListAdapter {
	public static final int GROUP_ID_UPDATING = 0;
	public static final int GROUP_ID_NEED_UPDATE = 1;
	public static final int GROUP_ID_INSTALLED = 2;
	private LayoutInflater inflater;
	Cursor updatingCursor;
	private Vector<DataSetObserver> mObservers;
	List<String> group; // 组列表
	List<ArrayList<AudioValueDownloadItem>> child; // 子列表
	private Context mContext;
	private ArrayList<AppInfoBean> needUpdateList, installedList ;
	private ExpandableListView mListView;
	private ChangeObserver mChangeObserver;
	private DownloadManager mDownloadManager;
	private PackageManager pm ;
	private final int PAUSE = 1;
	private final int RESUME = 2;
	private final int INSTALL = 3;
	private final int UPDATE = 4;
	private final int DELETE = 5;
	
	
	
	public AppManagerAdapter(Context context, Cursor updatingCursor, ArrayList<AppInfoBean> needUpdateList, 
			ArrayList<AppInfoBean> installedList, ExpandableListView mListView) {
		inflater = LayoutInflater.from(context);
		mContext = context;
		mObservers = new Vector<DataSetObserver>();
		this.updatingCursor = updatingCursor;
		this.needUpdateList = needUpdateList;
		this.installedList = installedList;
		this.mListView = mListView;
		mChangeObserver = new ChangeObserver();
		group = new ArrayList<String>();
		child = new ArrayList<ArrayList<AudioValueDownloadItem>>();
		initializeData(context);
		mDownloadManager = new DownloadManager(mContext);
		pm = MarketApplication.getMarketAppContext().getPackageManager();
	}
	
	
	
	

	public ArrayList<AppInfoBean> getNeedUpdateList() {
		return needUpdateList;
	}


	public void setNeedUpdateList(ArrayList<AppInfoBean> needUpdateList) {
		this.needUpdateList = needUpdateList;
	}


	public ArrayList<AppInfoBean> getInstalledList() {
		return installedList;
	}


	public void setInstalledList(ArrayList<AppInfoBean> installedList) {
		this.installedList = installedList;
	}





	private class ChangeObserver extends ContentObserver {
		public ChangeObserver() {
			super(new Handler());
		}

		@Override
		public boolean deliverSelfNotifications() {
			return true;
		}

		@Override
		public void onChange(boolean selfChange) {
			Log.e("onChange", "AppManagerAdapter onChange");
			refreshData();
		}
	}

	void refreshData() {
		if (updatingCursor.isClosed()) {
			return;
		}
		updatingCursor.requery();
		for (DataSetObserver o : mObservers) {
			o.onChanged();
		}
		//initializeCursorData();
		//initializeData(mContext, false);
		refreshCursorData();
	}

	
	public void refreshCursorData(){
		ArrayList<AudioValueDownloadItem> childitem = new ArrayList<AudioValueDownloadItem>();
		if (updatingCursor != null && updatingCursor.getCount() != 0) {
			for (updatingCursor.moveToFirst(); !updatingCursor.isAfterLast(); updatingCursor
					.moveToNext()) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				audioValueDownloadItem.id = updatingCursor
				.getLong(updatingCursor
						.getColumnIndex(Downloads.Impl._ID));
				audioValueDownloadItem.title = updatingCursor
						.getString(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_TITLE));
				audioValueDownloadItem.description = updatingCursor
						.getString(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_DESCRIPTION));
				audioValueDownloadItem.status = updatingCursor
						.getInt(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_STATUS));
				audioValueDownloadItem.totalBytes = updatingCursor
						.getLong(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_TOTAL_BYTES));
				audioValueDownloadItem.currentBytes = updatingCursor
						.getLong(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_CURRENT_BYTES));
				audioValueDownloadItem.packageName = updatingCursor
						.getString(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_PACKAGE_NAME));
				childitem.add(audioValueDownloadItem);
			}
		}
		child.set(GROUP_ID_UPDATING, childitem);
	}
	
	public void refreshNeedUpdateData(){
		ArrayList<AudioValueDownloadItem> childitem = new ArrayList<AudioValueDownloadItem>();
		if (needUpdateList != null) {
			for (AppInfoBean appinfo : this.needUpdateList) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				audioValueDownloadItem.title = appinfo.APP_NAME;
				audioValueDownloadItem.icon = appinfo.APP_ICON_BMP;
				audioValueDownloadItem.version = appinfo.APP_VER;
				childitem.add(audioValueDownloadItem);
			}
		}
		child.set(GROUP_ID_NEED_UPDATE, childitem);
	}
	
	
	public void refreshInstalledData(){
		ArrayList<AudioValueDownloadItem> childitem = new ArrayList<AudioValueDownloadItem>();
		if (installedList != null) {
			for (AppInfoBean appinfo : this.installedList) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				audioValueDownloadItem.title = appinfo.APP_NAME;
				audioValueDownloadItem.icon = appinfo.APP_ICON_BMP;
				audioValueDownloadItem.version = appinfo.APP_VER;
				childitem.add(audioValueDownloadItem);
			}
		}
		child.set(GROUP_ID_INSTALLED, childitem);
	}
	
	/**
	 * 初始化组、子列表数据
	 */
	public void initializeData(Context context) {
		group.clear();
		child.clear();
		String groupName = "";
		groupName = "正在更新";
		ArrayList<AudioValueDownloadItem> childitem = new ArrayList<AudioValueDownloadItem>();
		if (updatingCursor != null) {
			for (updatingCursor.moveToFirst(); !updatingCursor.isAfterLast(); updatingCursor
					.moveToNext()) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				audioValueDownloadItem.id = updatingCursor
				.getLong(updatingCursor
						.getColumnIndex(Downloads.Impl._ID));
				audioValueDownloadItem.title = updatingCursor
						.getString(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_TITLE));
				audioValueDownloadItem.description = updatingCursor
						.getString(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_DESCRIPTION));
				audioValueDownloadItem.status = updatingCursor
						.getInt(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_STATUS));
				audioValueDownloadItem.totalBytes = updatingCursor
						.getLong(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_TOTAL_BYTES));
				audioValueDownloadItem.currentBytes = updatingCursor
						.getLong(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_CURRENT_BYTES));
				audioValueDownloadItem.packageName = updatingCursor
						.getString(updatingCursor
								.getColumnIndex(Downloads.Impl.COLUMN_PACKAGE_NAME));
				childitem.add(audioValueDownloadItem);
			}
		}
		addAudioInfo(groupName, childitem);

		groupName = "可更新";
		childitem = new ArrayList<AudioValueDownloadItem>();
		if (needUpdateList != null) {
			for (AppInfoBean appinfo : this.needUpdateList) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				audioValueDownloadItem.title = appinfo.APP_NAME;
				audioValueDownloadItem.icon = appinfo.APP_ICON_BMP;
				audioValueDownloadItem.version = appinfo.APP_VER;
				childitem.add(audioValueDownloadItem);
			}
		}
		addAudioInfo(groupName, childitem);
		
		groupName = "已安装";
		childitem = new ArrayList<AudioValueDownloadItem>();
		if (installedList != null) {
			for (AppInfoBean appinfo : this.installedList) {
				AudioValueDownloadItem audioValueDownloadItem = new AudioValueDownloadItem();
				
				audioValueDownloadItem.title = appinfo.APP_NAME;
				audioValueDownloadItem.icon = appinfo.APP_ICON_BMP;
				audioValueDownloadItem.version = appinfo.APP_VER;
				childitem.add(audioValueDownloadItem);
			}
		}
		addAudioInfo(groupName, childitem);

	}

	private void addAudioInfo(String g,
			ArrayList<AudioValueDownloadItem> valueItem) {
		group.add(g);
		child.add(valueItem);
	}

	private class AudioDownloadItem {
		private ImageView icon;
		private TextView title;
		private TextView downloadProgress;
		private ImageView controlBtn;
		private LinearLayout btnView;
		private TextView btnText;
	}

	public class AudioValueDownloadItem {
		public long id;
		public String title;
		public String description;
		public int status;
		public long totalBytes;
		public long currentBytes;
		public Drawable icon;
		public int version;
		public String packageName;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		String string = group.get(groupPosition);
		View view = inflater.inflate(R.layout.appdownload_group_layout,
				null);
		TextView downGroupInfoView = (TextView) view
				.findViewById(R.id.download_group_title);
		ImageView downGroupIndicator = (ImageView) view
				.findViewById(R.id.download_group_Indicator);
		downGroupInfoView.setText(string);
		if (isExpanded) {
			downGroupIndicator.setImageResource(R.drawable.download_group_open);
		} else {
			downGroupIndicator.setImageResource(R.drawable.download_group_close);
		}
		return view;
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return child.get(groupPosition).get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return 0;
	}

	@Override
	public View getChildView(final int groupPosition, final int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		if(child.get(groupPosition).isEmpty()){
			return convertView;
		}
		final AudioValueDownloadItem childItem = child.get(groupPosition).get(
				childPosition);
		final AudioDownloadItem audioDownloadItem;
		if (null == convertView) {
			convertView = inflater.inflate(R.layout.appdownload_adapter, null);
			audioDownloadItem = new AudioDownloadItem();
			audioDownloadItem.icon = (ImageView) convertView
			        .findViewById(R.id.download_icon);
			audioDownloadItem.title = (TextView) convertView
					.findViewById(R.id.download_title);
			audioDownloadItem.downloadProgress = (TextView) convertView
					.findViewById(R.id.progress_text);
			audioDownloadItem.btnText = (TextView) convertView
			        .findViewById(R.id.btn_text);
			audioDownloadItem.btnView = (LinearLayout) convertView
	                .findViewById(R.id.btn_group);
			audioDownloadItem.controlBtn = (ImageView) convertView
					.findViewById(R.id.control_btn);
			
			audioDownloadItem.btnView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					AppInfoBean appinfo = null;
					Object id = ((View) v.getParent()).getTag();
					if (id != null) {
						switch ((Integer) audioDownloadItem.btnView.getChildAt(0).getTag()) {
						case PAUSE:
//							Toast.makeText(mContext, "pause", Toast.LENGTH_SHORT).show();
							pauseDownload((Long)id);
							audioDownloadItem.controlBtn.setTag(RESUME);
							audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_resume);
							break;
						case RESUME:
//							Toast.makeText(mContext, "resume", Toast.LENGTH_SHORT).show();
							resumeDownload((Long)id);
							audioDownloadItem.controlBtn.setTag(PAUSE);
						    audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_pause);
							break;
						case INSTALL:
//							Toast.makeText(mContext, "install", Toast.LENGTH_SHORT).show();
						    Cursor c = mContext.getContentResolver().query(
									ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI,
											(Long)id), null, null, null, null);
						    c.moveToFirst();
						    Intent i = new Intent(Intent.ACTION_VIEW); 
						    String filePath = c.getString(c.getColumnIndex(Downloads.Impl._DATA)); 
						    i.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive"); 
						    mContext.startActivity(i);
	                        c.close();
							break;
						case UPDATE:
//							Toast.makeText(mContext, "update", Toast.LENGTH_SHORT).show();
						    appinfo = needUpdateList.get((Integer)id);
	                    	needUpdateList.remove(((Integer)id).intValue());
	                    	refreshNeedUpdateData();
	                    	mDownloadManager.insertDownload(appinfo, Downloads.TYPE_UPDATE);
							break;
						case DELETE:
//							Toast.makeText(mContext, "delete", Toast.LENGTH_SHORT).show();
						    appinfo = installedList.get((Integer)id);
							Uri uri = Uri.fromParts("package", appinfo.APP_PACK, null);
							Intent uninstallIntent = new Intent(
									Intent.ACTION_DELETE, uri);
							mContext.startActivity(uninstallIntent);
							break;
						}
				}
				}
			});
			
			
			
//			audioDownloadItem.controlBtn.setOnClickListener(new View.OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						AppInfoBean appinfo = null;
//						Object id = ((View) v.getParent().getParent()).getTag();
//						if (id != null) {
//								switch ((Integer) v.getTag()) {
//								case PAUSE:
//									Toast.makeText(mContext, "pause", Toast.LENGTH_SHORT).show();
//									pauseDownload((Long)id);
//									audioDownloadItem.controlBtn.setTag(RESUME);
//									audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_resume);
//									break;
//								case RESUME:
//									Toast.makeText(mContext, "resume", Toast.LENGTH_SHORT).show();
//									resumeDownload((Long)id);
//									audioDownloadItem.controlBtn.setTag(PAUSE);
//								    audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_pause);
//									break;
//								case INSTALL:
//									Toast.makeText(mContext, "install", Toast.LENGTH_SHORT).show();
//								    Cursor c = mContext.getContentResolver().query(
//											ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI,
//													(Long)id), null, null, null, null);
//								    c.moveToFirst();
//								    Intent i = new Intent(Intent.ACTION_VIEW); 
//								    String filePath = c.getString(c.getColumnIndex(Downloads.Impl._DATA)); 
//								    i.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive"); 
//								    mContext.startActivity(i);
//			                        c.close();
//									break;
//								case UPDATE:
//									Toast.makeText(mContext, "update", Toast.LENGTH_SHORT).show();
//								    appinfo = needUpdateList.get((Integer)id);
//			                    	needUpdateList.remove(((Integer)id).intValue());
//			                    	refreshNeedUpdateData();
//			                    	mDownloadManager.insertDownload(appinfo, Downloads.TYPE_UPDATE);
//									break;
//								case DELETE:
//									Toast.makeText(mContext, "delete", Toast.LENGTH_SHORT).show();
//								    appinfo = installedList.get((Integer)id);
//									Uri uri = Uri.fromParts("package", appinfo.APP_PACK, null);
//									Intent uninstallIntent = new Intent(
//											Intent.ACTION_DELETE, uri);
//									mContext.startActivity(uninstallIntent);
//									break;
//								}
//						}
//					}
//				});
			
			convertView.setTag(R.layout.appdownload_adapter, audioDownloadItem);
		} else {
			audioDownloadItem = (AudioDownloadItem) convertView
					.getTag(R.layout.appdownload_adapter);
		}
		if(childItem.icon != null){
			audioDownloadItem.icon.setBackgroundDrawable(childItem.icon);
		} else {
			PackageInfo packageInfo;
			try {
				packageInfo = pm.getPackageInfo(childItem.packageName,0);
				Drawable d = packageInfo.applicationInfo.loadIcon(pm);
				if(d != null) {
					Log.e("icon", "d != null" + childItem.packageName);
					audioDownloadItem.icon.setBackgroundDrawable(d);
				} else {
					Log.e("icon", "d = null" + childItem.packageName);
					audioDownloadItem.icon.setBackgroundResource(R.drawable.icon);
				}
			} catch (NameNotFoundException e) {
				Log.e("icon", "NameNotFoundException = null" + childItem.packageName);
				audioDownloadItem.icon.setBackgroundResource(R.drawable.icon);
				e.printStackTrace();
			}
			
		}
		audioDownloadItem.title.setText(childItem.title);
		switch (groupPosition){
		case GROUP_ID_UPDATING:
			Log.e("onChange", "getChildView--GROUP_ID_UPDATING");
			audioDownloadItem.btnText.setVisibility(View.VISIBLE);
			audioDownloadItem.downloadProgress.setVisibility(View.VISIBLE);
			int progressAmount = 0;
			if (childItem.totalBytes != 0)
				progressAmount = (int) (childItem.currentBytes * 100 / childItem.totalBytes);
			if (Downloads.isStatusCompleted(childItem.status)) { // Download stopped
				if (Downloads.isStatusError(childItem.status)) {
					audioDownloadItem.controlBtn.setTag(RESUME);
					audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_resume);
					audioDownloadItem.btnText.setText("继续");
					audioDownloadItem.downloadProgress.setTextColor(Color.parseColor("#AA947F"));
					audioDownloadItem.downloadProgress.setText("已暂停" + progressAmount + "%");
				} else {
					audioDownloadItem.controlBtn.setTag(INSTALL);
					audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_install);
					audioDownloadItem.btnText.setText("安装");
					audioDownloadItem.downloadProgress.setVisibility(View.GONE);
				}
			} else { // Download is still running
				if (childItem.status == Downloads.STATUS_PENDING) {
					audioDownloadItem.controlBtn.setTag(PAUSE);
					audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_pause);
					audioDownloadItem.btnText.setText("暂停");
					audioDownloadItem.downloadProgress.setTextColor(Color.parseColor("#1E9320"));
					audioDownloadItem.downloadProgress.setText("正在下载" + progressAmount + "%");
				} else if (childItem.status == Downloads.STATUS_PENDING_PAUSED) {
					audioDownloadItem.controlBtn.setTag(PAUSE);
					audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_pause);
					audioDownloadItem.btnText.setText("暂停");
					audioDownloadItem.downloadProgress.setTextColor(Color.parseColor("#1E9320"));
					audioDownloadItem.downloadProgress.setText("正在下载" + progressAmount + "%");
				} else {
					if (childItem.status == Downloads.STATUS_RUNNING) {
						audioDownloadItem.controlBtn.setTag(PAUSE);
						audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_pause);
						audioDownloadItem.btnText.setText("暂停");
						audioDownloadItem.downloadProgress.setTextColor(Color.parseColor("#1E9320"));
						audioDownloadItem.downloadProgress.setText("正在下载" + progressAmount + "%");
					} else {
						audioDownloadItem.controlBtn.setTag(RESUME);
						audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.download_resume);
						audioDownloadItem.btnText.setText("继续");
						audioDownloadItem.downloadProgress.setTextColor(Color.parseColor("#AA947F"));
						audioDownloadItem.downloadProgress.setText("已暂停" + progressAmount + "%");
					}
				}
			}
			convertView.setTag(childItem.id);
			break;
		case GROUP_ID_NEED_UPDATE:
			Log.e("onChange", "getChildView--GROUP_ID_NEED_UPDATE");
			audioDownloadItem.controlBtn.setTag(UPDATE);
			audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.app_update);
			audioDownloadItem.btnText.setText("更新");
			audioDownloadItem.downloadProgress.setVisibility(View.GONE);
			convertView.setTag(childPosition);
			break;
		case GROUP_ID_INSTALLED:
			Log.e("onChange", "getChildView--GROUP_ID_INSTALLED");
			audioDownloadItem.controlBtn.setTag(DELETE);
			audioDownloadItem.controlBtn.setBackgroundResource(R.drawable.app_delete);
			audioDownloadItem.btnText.setText("卸载");
			audioDownloadItem.downloadProgress.setVisibility(View.GONE);
			convertView.setTag(childPosition);
			break;
		}
		
		return convertView;
	}
	
	
	 public void pauseDownload(long id) {
			pauseDownload(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, id));
		}

		public void pauseDownload(Uri uri) {

			ContentValues values = new ContentValues();
			values
					.put(Downloads.Impl.COLUMN_CONTROL,
							Downloads.Impl.CONTROL_PAUSED);
			mContext.getContentResolver().update(uri, values, null, null);
		}
		
		public void resumeDownload(long id) {
			resumeDownload(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, id));
		}

		public void resumeDownload(Uri uri) {

			ContentValues values = new ContentValues();
			values.put(Downloads.Impl.COLUMN_CONTROL, Downloads.Impl.CONTROL_RUN);
			mContext.getContentResolver().update(uri, values, null, null);
		}

	@Override
	public int getChildrenCount(int groupPosition) {
		return child.get(groupPosition).size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return group.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		return group.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return 0;
	}

	@Override
	public boolean hasStableIds() {
		return false;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

	public void registerDataSetObserver(DataSetObserver observer) {
		mObservers.add(observer);
	}

	public void unregisterDataSetObserver(DataSetObserver observer) {
		mObservers.remove(observer);
	}
	
	public void registerContentObserver() {
		if (mChangeObserver != null) {
			updatingCursor.registerContentObserver(mChangeObserver);
		}
		
	}

	public void unregisterContentObserver() {
		if (mChangeObserver != null) {
			updatingCursor.unregisterContentObserver(mChangeObserver);
		}
		
	}
	
}
